<?php
namespace App\Think\SdkGame;

class AGZR{

  // api文档 https://documenter.getpostman.com/view/4224711/SzS7RS1q?version=latest
  // https://member.pebet.cc/Home/Index
  // 账号/baote123    
  // 密碼/aabb123

    public function __construct()
    {
        // api地址
        $this->api_url  = 'http://api198.pe2020888.me/';
        $this->pull_url = 'https://record.pe2020888.me/';

        $this->DESKey = '5AXv2ixU';
        $this->WebSiteCode = '1C1B8E79-B35C-40D6-B964-D9C460FD750C';

        $this->plat_type  = 'AGZR';
        $this->platformCode = 'AG';

        $this->password_init = 'baote123A';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            'platformCode' => $this->platformCode,
            'userName'     => $param['account'],
            'userPassWord' => $this->password_init,
            'TimeStamp'    => time(),
        );
        $url = $this->build_url('api','api/Register', $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){

        // $reg_res = $this->register($param);
        $req_data = array(
            'platformCode' => $this->platformCode,
            'userName'     => $param['account'],
            'userPassWord' => $this->password_init,
            'gameType'     => 0,
            'devices'      => 0,
            'lang'         => 1,
            'TimeStamp'    => time(),
        );
        $url = $this->build_url('api', 'api/GetLoginUrl', $req_data);
        $res = $this->sendRequest($url);
        return ['code'=>$res['code'], 'url'=>$res['msg'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            'platformCode' => $this->platformCode,
            'userName'     => $param['account'],
            'userPassWord' => $this->password_init,
            'TimeStamp'    => time(),
        );
        $url = $this->build_url('api', 'api/GetUserBalance', $req_data);
        $res = $this->sendRequest($url);
        return ['code'=>$res['code'], 'balance'=>(float)$res['msg'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'platformCode' => $this->platformCode,
            'userName'     => $param['account'],
            'userPassWord' => $this->password_init,
            'transferType' => 'IN',
            'credit'       => $param['money'],
            'TimeStamp'    => time(),
        );
        $url = $this->build_url('api', 'api/Transfer', $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'platformCode' => $this->platformCode,
            'userName'     => $param['account'],
            'userPassWord' => $this->password_init,
            'transferType' => 'OUT',
            'credit'       => $param['money'],
            'TimeStamp'    => time(),
        );
        $url = $this->build_url('api', 'api/Transfer', $req_data);
        $res = $this->sendRequest($url);
        return $res;
    }

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            'platformCode' => $this->platformCode,
            'startTime'    => strtotime($param['startTime']),
            'endTime'      => strtotime($param['endTime']),
            'pageIndex'    => 1,
            'pageSize'     => 100000,
            // 'TimeStamp'    => time(),
        );
        $url = $this->build_url('pull', 'QueryApi/GetMerchantReport', $req_data);
        $res = $this->sendRequest($url);

        //数据返回处理
        $list = @$res['data'];
        // print_r($list);
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {

                //流水
                if($v['netPnl'] < 0)  $money_valid = -$v['netPnl']<$v['betAmount'] ? -$v['netPnl'] : $v['betAmount'];
                if($v['netPnl'] >= 0) $money_valid = $v['netPnl']<$v['betAmount'] ? $v['netPnl'] : $v['betAmount'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['gameCode'],
                    'game_name'     => $this->game_name($v['gameCode']),
                    'game_user'     => $v['username'],
                    'bet_id'        => $v['betOrderNo'],
                    'money_bet'     => $v['betAmount'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $v['netPnl'],
                    'money_fee'     => 0,
                    'createtime'    => strtotime($v['gameStartTime']),
                    'updatetime'    => strtotime($v['gameEndTime']),
                    'status'        => 1,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['betOrderNo'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['gameEndTime']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -101 ? 1 : $res['code'];
        return $res;
    }


    /**
     * 业务 ======== start =========//
     */
    //游戏列表
    public function game_list(){
        $res = file_get_contents(dirname(__FILE__).'/AGZR_data.txt');
        $list = json_decode($res, true);
        return $list;
    }
    //游戏名称
    public function game_name($gameCode){
        $list = $this->game_list();
        foreach ($list as $k => $v) {
          if($v['gameType'] == $gameCode) return $v['gameName'];
        }
        return '未知游戏';
        // return isset($list[$gameType]) ? $list[$gameType] : '未知游戏';
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url, $post_data=array(), $req_type=0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 

        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);
        // print_r($contents);
        //业务处理
        // $res = $contents;
        if(!isset($contents['retCode'])){
          $res['code'] = -1;
          return $res;  
        } 
        if($contents['retCode'] == 0){
            $res['code'] = 1;  
        }else{
            $res['code'] = $contents['retCode'] > 0 ? -$contents['retCode'] : -1;
        }
        $res['msg']  = $contents['retMsg'];
        $res['data'] = @$contents['data'];
        return $res;
    }

    
    private function build_url($type='api', $act='', $param){
        $JoDES = new JoDES();
        $param =  http_build_query($param);
        $parameter = $JoDES->encode($param, $this->DESKey);
        $api_url = ($type=='pull') ? $this->pull_url : $this->api_url;
        return $api_url.$act."?parameter={$parameter}"."&WebSiteCode={$this->WebSiteCode}";
    }

}





class JoDES {
  private static $_instance = NULL;
  /**
   * @return JoDES
   */
  public static function share() {
      if (is_null(self::$_instance)) {
          self::$_instance = new JoDES();
      }
      return self::$_instance;
  }

  /**
   * 加密
   * @param string $str 要处理的字符串
   * @param string $key 加密Key，为8个字节长度
   * @return string
   */
  public function encode($str, $key) {
      $str=str_replace('+','%2b',$str);
      $size = @mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
      $str = $this->pkcs5Pad($str, $size);
      // $aaa = mcrypt_cbc(MCRYPT_DES, $key, $str, MCRYPT_ENCRYPT, $key);
      $aaa = @mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_CBC, $key);
      $ret = base64_encode($aaa);
      return urlencode($ret);
  }

  /**
   * 解密
   * @param string $str 要处理的字符串
   * @param string $key 解密Key，为8个字节长度
   * @return string
   */
  public function decode($str, $key) {
      $strPen = base64_decode($str);
      // $str = mcrypt_cbc(MCRYPT_DES, $key, $strPen, MCRYPT_DECRYPT, $key);
      $str = @mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_CBC, $key);
      $str = $this->pkcs5Unpad($str);
      return $str;
  }

  function hex2bin($hexData) {
      $penData = "";
      for ($i = 0; $i < strlen($hexData); $i += 2) {
          $penData .= chr(hexdec(substr($hexData, $i, 2)));
      }
      return $penData;
  }

  function pkcs5Pad($text, $blocksize) {
      $pad = $blocksize - (strlen($text) % $blocksize);
      return $text . str_repeat(chr($pad), $pad);
  }

  function pkcs5Unpad($text) {
      $pad = ord($text {strlen($text) - 1});
      if ($pad > strlen($text))
          return false;

      if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
          return false;

      return substr($text, 0, - 1 * $pad);
  }
}


